//
//  RHMeOrgnizationList.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/20.
//

#import "RHMeOrgnizationListVC.h"
#import "RHMeOrgnizationListCell.h"
#import "RHMeOrgnizationModel.h"
#import "RHSearchView.h"
#import "RHAddCommonModel.h"

@interface RHMeOrgnizationListVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic, strong) RHMeOrgnizationModel *OrgModel;//最上层组织

@property (nonatomic, strong) NSMutableArray *selectOrgArr;//当前选择的(上面已选展示)

@property (nonatomic, strong) RHMeOrgnizationModel *selectOrgModel;//当前选择的

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic, copy) NSString *keyCode;//搜索

@property (nonatomic, strong) UIView *containView;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableArray *labelArr;

@property (nonatomic ,strong) NSMutableArray *searchOrgArr;
@end

@implementation RHMeOrgnizationListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"选择组织".rh_localized;
  
    [self setupUI];
    [self getOrgnizationList];
}



- (void)setupUI{
    kWeakSelf;
    self.labelArr     = [NSMutableArray array];
    self.selectOrgArr = [NSMutableArray array];
    self.searchOrgArr = [NSMutableArray array];
    //搜索栏
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 45)];
    _searchView.isAutoHideSearchButton = NO;
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入关键字".rh_localized;
    
    UIView *orgView = [self orgView];
    [self.view addSubview:orgView];
    [orgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.height.offset(40);
    }];
    
    QMUIButton *addButton = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [addButton setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addButton setBackgroundColor:CMainColorGreen];
    [addButton.layer setCornerRadius:5];
    [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [addButton addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addButton];

    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15)];
   
    [_tableView registerClass:[RHMeOrgnizationListCell class] forCellReuseIdentifier:@"RHMeOrgnizationListCell"];
    [self.view addSubview:_tableView];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(orgView.mas_bottom);
        make.bottom.equalTo(addButton.mas_top).offset(-15);
    }];
    
    
}

-(UIView*)orgView
{
    UIView *bgView = kView;
    bgView.backgroundColor = UIColor.whiteColor;
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    [bgView addSubview:scrollView];
    self.scrollView = scrollView;
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *containView = kView;
    containView.backgroundColor = UIColor.whiteColor;
    [scrollView addSubview:containView];
    self.containView = containView;
    [containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.height.equalTo(bgView);
    }];
    return bgView;
}

-(void)updateOrgView
{
    for (QMUILabel *lab in self.labelArr) {
        lab.hidden = YES;
    }
    [self.containView qmui_removeAllSubviews];
    kWeakSelf;
    __block UIView *lastLab;
    [self.selectOrgArr enumerateObjectsUsingBlock:^(RHMeOrgnizationModel*  _Nonnull orgModel, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUILabel *lab = [weakSelf.labelArr safeObjectAtIndex:idx];
       
        lab.hidden = NO;
        if (lab==nil) {
            lab = [QMUILabel labelWithText:orgModel.orgName font:kSYSTEMFONT(14) textColor:kCOLOR_HEX(@"#05C79D")];
            lab.tag = idx;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
            [tap addTarget:self action:@selector(tapAction:)];
            [lab addGestureRecognizer:tap];
            [weakSelf.labelArr addObject:lab];
        }
        lab.text = orgModel.orgName;
        if (idx == weakSelf.selectOrgArr.count - 1) {
            lab.textColor = kCOLOR_HEX(@"#8B8D92");
            lab.userInteractionEnabled = NO;
        }else{
            lab.textColor = kCOLOR_HEX(@"#05C79D");
            lab.text = [NSString stringWithFormat:@"%@ ＞",lab.text];
            lab.attributedText = [NSString attributeStringWithContent:lab.text attriFont:lab.font attriColor:kCOLOR_HEX(@"#8B8D92") attriKey:@"＞"];
            
            lab.userInteractionEnabled = YES;
        }
     
        [weakSelf.containView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastLab) {
                make.left.equalTo(lastLab.mas_right).offset(5);
            }else{
                make.left.mas_offset(10);
            }
            make.centerY.mas_offset(0);
//            make.width.offset(width+10);
        }];
        lastLab = lab;
    }];
    [lastLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-10);
    }];
    
}

-(void)sureAction
{
    RHMeOrgnizationModel *orgModel = [self.selectOrgArr lastObject];
    if (self.selectBlock) {
        self.selectBlock(orgModel);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)tapAction:(UIGestureRecognizer*)gesture
{
    [self clearAllModelStatus:self.OrgModel];
    
    QMUILabel *lab = (QMUILabel*)gesture.view;
    NSMutableArray *mtbArr = [NSMutableArray array];
    [self.selectOrgArr enumerateObjectsUsingBlock:^(RHMeOrgnizationModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx>lab.tag) {
            [mtbArr addObject:obj];
        }
    }];
    self.selectOrgModel = [self.selectOrgArr safeObjectAtIndex:lab.tag];
    [self.selectOrgArr removeObjectsInArray:mtbArr];
    [self updateOrgView];
    [self.tableView reloadData];
    
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchOrgArr.count>0) {
        return self.searchOrgArr.count;
    }
    return self.selectOrgModel.childrenList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    RHMeOrgnizationListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMeOrgnizationListCell"];
    
    RHMeOrgnizationModel *model = [self.selectOrgModel.childrenList safeObjectAtIndex:indexPath.row];
    if (self.searchOrgArr.count>0) {
        model = [self.searchOrgArr safeObjectAtIndex:indexPath.row];
    }
    cell.orgModel = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BOOL hasNext = (model.childrenList.count!=0)&&(model.orgType!=OrganizationTypeUser);
    [cell showArrow:hasNext];
    kWeakSelf;
    cell.selectBlock = ^(RHMeOrgnizationModel * _Nonnull model) {
        [weakSelf selectOrgnization:model];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果之前在同一层选了其他的组织,而且是最后一层,要删除掉
    __block RHMeOrgnizationModel *lastSelectModel;
    [self.selectOrgModel.childrenList enumerateObjectsUsingBlock:^(RHMeOrgnizationModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            lastSelectModel = obj;
            *stop = YES;
        }
    }];
    if ([self.selectOrgArr containsObject:lastSelectModel]) {
        [self.selectOrgArr removeObject:lastSelectModel];
    }
    
    //清除所有状态
    [self clearAllModelStatus:self.OrgModel];
    
    RHMeOrgnizationModel *model = [self.selectOrgModel.childrenList safeObjectAtIndex:indexPath.row];
    if (self.searchOrgArr.count>0) {
        model = [self.searchOrgArr safeObjectAtIndex:indexPath.row];
    }
    
    RHMeOrgnizationModel *lastModel = [self.selectOrgArr lastObject];
    //如果点击的还有下级, 有的orgTYpe = 3的还有下级,判断一下
    if (model.childrenList.count>0 && (model.orgType != OrganizationTypeUser)) {
        
        
        self.selectOrgModel = model;
        if (model && ![self.selectOrgArr containsObject:model]) {
            [self.selectOrgArr addObject:model];
            [self updateOrgView];
        }
    }else{
        //已经是最后一级
        //没有添加过
        model.isSelected = YES;
        if (lastModel.orgType != OrganizationTypeUser) {
            if (![self.selectOrgArr containsObject:model]) {
                [self.selectOrgArr addObject:model];
            }
            
        }
        [self updateOrgView];
        
    }
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGFloat offset = self.scrollView.contentSize.width - self.scrollView.width;
        if (offset<0) {
            offset = 0;
        }
        [self.scrollView setContentOffset:CGPointMake(offset, 0) animated:YES];
    });
    
    [tableView reloadData];
}

//点击左边选择按钮
-(void)selectOrgnization:(RHMeOrgnizationModel*)model
{
    //移动上次所选
    __block RHMeOrgnizationModel *lastSelectModel;
    [self.selectOrgModel.childrenList enumerateObjectsUsingBlock:^(RHMeOrgnizationModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            lastSelectModel = obj;
            obj.isSelected = NO;
            *stop = YES;
        }
    }];
    if ([self.selectOrgArr containsObject:lastSelectModel]) {
        [self.selectOrgArr removeObject:lastSelectModel];
    }
    model.isSelected = YES;
    if (![self.selectOrgArr containsObject:model]) {
        [self.selectOrgArr addObject:model];
    }
    [self.tableView reloadData];
    [self updateOrgView];
}

//获取组织
-(void)getOrgnizationList
{
    [QMUITips showLoadingInView:kAppWindow];
    [RHMeOrgnizationModel startGetWithCompletionAPIKey:H_MeOrgnizationList argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200){
            
            self.OrgModel = resultModel.data;
            self.selectOrgModel = self.OrgModel;
            self.dataArr = self.OrgModel.childrenList;
            
            [self.selectOrgArr removeAllObjects];
            [self.selectOrgArr addObject:self.selectOrgModel];
            [self updateOrgView];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


-(void)clearAllModelStatus:(RHMeOrgnizationModel*)model
{
  
        [model.childrenList enumerateObjectsUsingBlock:^(RHMeOrgnizationModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelected = NO;
            [self clearAllModelStatus:obj];
            NSLog(@"---->name:%@",obj.orgName);
        }];
    
}


#pragma mark ------- textField delegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.searchOrgArr removeAllObjects];
    for (RHMeOrgnizationModel *model in self.selectOrgModel.childrenList) {
        if ([model.orgName.uppercaseString containsString:textField.text.uppercaseString]) {
            [self.searchOrgArr addObject:model];
        }
    }
    [self.tableView reloadData];
  
}


- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.searchOrgArr removeAllObjects];
    return YES;
}

@end
